import os
import json
from pydash import _
from pprint import pp
import pandas as pd

# 巴西mongo
keys = [
    [
        "AKIDADvVmrhJhqjRvBDz6GS5cw2sb5QXP2Sd",
        "ynOltlPoyviHbfU9bppaCajdJkwtc6LL",
        "hangzhou_hongzhi10@163.com",
        100042618069,
        "张江花",
    ],
    [
        "AKID76CJF1aDnEVfibIlF1iFj163oX3LZieU",
        "veMp4DB1jGgw30kHdnmbFh2C9tPipjT1",
        "悦恩途（微信)",
        100001485562,
    ],
    [
        "AKIDHTYQuFg08IYaSBi15vb5g5MTMRHxPiq1",
        "HLDuVzLUVMLF1ZxDG7sTwFNONG2f8Qad",
        "大麦数据-阿锋",
        100010424531,
    ],
    [
        "AKIDPhokV2QehYCcGerwrdFdnlrumeNuLchb",
        "BRfu0sa7SaXctGXeaIuMdiZn01nojU2P",
        "hangzhou_hongzhi_3@163.com",
        100022130614,
        "李小玲",
    ],
    [
        "AKID9LWg5TxQj1Y1RmzNfryUuSC404MmEdip",
        "GZp9X5Te0UHFHIQQE6virARp6Z1UA6HZ",
        "hangzhou_hongzhi_6@163.com",
        100023842635,
        "李小玲",
    ],
    [
        "AKIDRmwseDYjhZEgvxDHArLchYDet1zoRr5A",
        "yiHfsUzKrNn396CSZaSAjARbeXGnANOC",
        "hangzhou_hongzhi_2@163.com",
        100021992162,
    ],
    [
        "AKIDpX3NUOAoIagYFj1MVSCj3EF3g8WigU7Y",
        "4va2HJ8h2B8sa5NSKgpnZ8TbZLvJUTEm",
        "大麦数据技术客服 阿锋",
    ],
    [
        "AKIDIzd3Hj5DAXsBIBsMgnfLzAC4kEVtGLSZ",
        "50idMyNZZO7dSCwWt20nT6XpyxkKl7Sh",
        "hangzhou_hongzhi_5@163.com",
        100022594234,
    ],
    [
        "AKIDEOL4ZqwpUu4lFZfV6VlsmRuBEFUiz82i",
        "c099xeIrJj9NUipjYDi1DDvv2EH8mGcl",
        "163clf@163.com",
    ],
    [
        "AKIDEMI0VmqtjLkvteDZieNuELFxXvQsAQZZ",
        "31vhKsHXdeVCjATjqBUeeU7YyELK9pNm",
        "hangzhou_hongzhi@163.com",
        100019992464,
        "李小玲",
    ],
    [
        "AKIDyqcx9A4mKg6UgxEQSK2b0EKCBzZy97rN",
        "MYZN2c1b5Tn020oX6b1ED5nOr9OTM3bx",
        "chenlf_hi@126.com",
        100016633107,
    ],
    [
        "AKIDjLCwY4ibHl4DC2jO1UmqgPxIPMJvR5i9",
        "W7oLlz79yb4ShmUBoJl4GNNHIKG96xdE",
        "hangzhou_hongzhi_7@163.com",
        100024647409,
        "李小玲",
    ],
    [
        "AKIDKWVIzUu65qPlvrZEgx1vc6PXTCj3wd7O",
        "A7rOkvsb6OVO5TfeQ0ObbO1SghV7ZngM",
        "damaishuju@163.com",
        100015949349,
    ],
    [
        "AKID1vd7QD8uRn085ziU7rdCauHckkYDf5b3",
        "Z6gDWAlBVffR1xsjmiW7a5Zw63rU3O2e",
        "杭州市钱塘区剑鱼软件开发工作室-管理员-Yg",
        100027279729,
    ],
    [
        "AKIDJnJl6KNHwgnqkbsz6HbYyEQBvXzHbaVN",
        "rdIJSgqumT1KCwa4Qf0AD9yHXZQJFEEE",
        "isnoth@outlook.com",
    ],
    [
        "AKIDpUs9F8oLhWCesrdBVaR4ScXEvOddOwGL",
        "6yb0ABxVosjPqKbdT6WheNr792pOiokT",
        "isnothe@gmail.com",
    ],
    [
        "AKIDzvgEYeYJq8GDCyZWIq9KMCqHWYP3Wmrj",
        "TkqiLlz3tWzFH4h9QO7h8RbuOwQ1lVAf",
        "linyao.c@gmail.com",
    ],
    [
        "AKIDQipocFertiKi070d5PWDi6GCnEUVL3au",
        "ERTM3d5MkvuhKkz42pTxFVZOzsZ4KNEt",
        "木木",
    ],
    [
        "AKIDX1GMEsIVVIqCMMAlV3PkuKgohNo0xgAP",
        "3rSovnRr2ziDTaS5UeZGWcWCesrc9SWQ",
        "hangzhou_hongzhi_9@163.com",
        100028696635,
    ],
]


class Solutions:
    def get_one_account_server_raw(self, *args):
        id = args[0]
        key = args[1]
        account_name = args[2]
        os.environ["TENCENTCLOUD_SECRET_ID"] = id
        os.environ["TENCENTCLOUD_SECRET_KEY"] = key
        # data = os.popen('tccli lighthouse DescribeInstances  --region na-siliconvalley  --Limit 100 ').read()
        data = os.popen(
            "tccli cvm DescribeInstances  --region ap-guangzhou  --Limit 100 "
        ).read()
        return _.map(
            json.loads(data).get("InstanceSet"),
            lambda i: _.assign(
                i,
                {
                    "AccountName": account_name,
                    "tencent_id": _.get(args, 3),
                    "kefu": _.get(args, 4),
                },
            ),
        )

    def get_one_account_disk_raw(
        self,
        *args,
    ):
        id = args[0]
        key = args[1]
        account_name = args[2]

        os.environ["TENCENTCLOUD_SECRET_ID"] = id
        os.environ["TENCENTCLOUD_SECRET_KEY"] = key
        # data = os.popen('tccli lighthouse DescribeInstances  --region na-siliconvalley  --Limit 100 ').read()
        data = os.popen(
            "tccli  cbs DescribeDisks  --region ap-guangzhou  --Limit 100 "
        ).read()
        return _.map(
            json.loads(data).get("DiskSet"),
            lambda i: _.assign(
                i,
                {
                    "AccountName": account_name,
                    "tencent_id": _.get(args, 3),
                    "kefu": _.get(args, 4),
                },
            ),
        )

    def get_one_account_light_server_raw(self, *args):
        id = args[0]
        key = args[1]
        account_name = args[2]
        os.environ["TENCENTCLOUD_SECRET_ID"] = id
        os.environ["TENCENTCLOUD_SECRET_KEY"] = key
        # data = os.popen('tccli lighthouse DescribeInstances  --region na-siliconvalley  --Limit 100 ').read()
        data = os.popen(
            "tccli lighthouse DescribeInstances  --region na-siliconvalley  --Limit 100"
        ).read()
        return _.map(
            json.loads(data).get("InstanceSet"),
            lambda i: _.assign(
                i,
                {
                    "AccountName": account_name,
                    "tencent_id": _.get(args, 3),
                    "kefu": _.get(args, 4),
                },
            ),
        )

    def get_all_server_raw(self):
        instances = []
        for key in keys:
            instances += self.get_one_account_server_raw(*key)
        self.instances = instances

    def get_all_disk_raw(self):
        disks = []
        for key in keys:
            disks += self.get_one_account_disk_raw(*key)
        self.disks = disks

    def get_all_light_server_raw(self):
        light_instances = []
        # for key in keys[-4:]:
        for key in keys:
            light_instances += self.get_one_account_light_server_raw(*key)
        self.light_instances = light_instances

    def get_all_server_simple(self):
        self.get_all_server_raw()
        simple = (
            _(self.instances)
            .map(
                lambda i: {
                    "InstanceId": i.get("InstanceId"),
                    "InstanceName": i.get("InstanceName"),
                    "OsName": i.get("OsName"),
                    "PublicIpAddresses": _.get(i, "PublicIpAddresses.0"),
                    "PrivateIpAddresses": _.get(i, "PrivateIpAddresses.0"),
                    "AccountName": i.get("AccountName"),
                    "CPU": i.get("CPU"),
                    "Memory": i.get("Memory"),
                    "Zone": _.get(i, "Placement.Zone"),
                    "ExpiredTime": i.get("ExpiredTime"),
                    "days_left": (
                        pd.to_datetime(i.get("ExpiredTime") or "1970-01-01", utc=True)
                        # 直接获取带 UTC 时区的当前时间
                        - pd.Timestamp.now(tz="UTC")
                    ).days,
                    "InternetMaxBandwidthOut": _.get(
                        i, "InternetAccessible.InternetMaxBandwidthOut"
                    ),
                    "tencent_id": i.get("tencent_id"),
                    "kefu": i.get("kefu"),
                }
            )
            .value()
        )
        self.simple = simple
        return simple

    def get_all_disk_simple(self):
        self.get_all_disk_raw()
        disks_simple = (
            _(self.disks)
            .map(
                lambda i: {
                    "DiskName": i.get("DiskName"),
                    "DiskSize": i.get("DiskSize"),
                    "DiskUsage": i.get("DiskUsage"),
                    "AccountName": i.get("AccountName"),
                    "ExpiredTime": i.get("DeadlineTime"),
                    "days_left": (
                        pd.to_datetime(i.get("DeadlineTime")) - pd.Timestamp.today()
                    ).days,
                }
            )
            .value()
        )
        self.disks_simple = disks_simple
        return disks_simple

    def get_all_light_server_simple(self):
        self.get_all_light_server_raw()
        simple = (
            _(self.light_instances)
            .map(
                lambda i: {
                    "InstanceId": i.get("InstanceId"),
                    "InstanceName": i.get("InstanceName"),
                    "PublicIpAddresses": _.get(i, "PublicAddresses.0"),
                    "PrivateIpAddresses": _.get(i, "PrivateIpAddresses.0"),
                    "AccountName": i.get("AccountName"),
                    "CPU": i.get("CPU"),
                    "Memory": i.get("Memory"),
                    "Zone": _.get(i, "Placement.Zone"),
                    "ExpiredTime": i.get("ExpiredTime"),
                }
            )
            .value()
        )
        self.light_simple = simple

    def write_to_csv(self):
        df = pd.DataFrame(self.simple)
        df["date"] = pd.to_datetime(df["ExpiredTime"])
        df["days_left"] = pd.to_datetime(df["date"]) - pd.Timestamp.today().tz_localize(
            "UTC"
        )
        df["days_left"] = df["days_left"].dt.days
        df = df.sort_values(by="days_left")
        df.to_csv("servers2.csv", index=False, encoding="utf-8-sig")

    def write_to_csv_disk(self):
        df = pd.DataFrame(self.disks_simple)
        df["date"] = pd.to_datetime(df["ExpiredTime"])
        df["days_left"] = pd.to_datetime(df["date"]) - pd.Timestamp.today()
        df["days_left"] = df["days_left"].dt.days
        df = df.sort_values(by="days_left")
        df.to_csv("disk_out.csv", index=False, encoding="utf-8-sig")

    def write_to_csv_light(self):
        df = pd.DataFrame(self.light_simple)
        df["date"] = pd.to_datetime(df["ExpiredTime"])
        df["days_left"] = pd.to_datetime(df["date"]) - pd.Timestamp.today().tz_localize(
            "UTC"
        )
        df["days_left"] = df["days_left"].dt.days
        df = df.sort_values(by="days_left")
        df.to_csv(f"light_servers.csv", index=False, encoding="utf-8-sig")


if __name__ == "__main__":
    ss = Solutions()
    print("get_all_server_simple")
    ss.get_all_server_simple()
    print("write_to_csv")
    ss.write_to_csv()
    print("get_all_disk_simple")
    ss.get_all_disk_simple()
    print("write_to_csv_disk")
    ss.write_to_csv_disk()
    print("get_all_light_server_simple")
    ss.get_all_light_server_simple()
    print("write_to_csv_light")
    ss.write_to_csv_light()
    print("done")
